"""
File   : 01_3_3_functions.py
Desc   : 工具调用 function calling
Date   : 2024/11/27
Author : Tianyu Chen
https://platform.openai.com/docs/guides/function-calling#function-calling-with-structured-outputs
"""

from openai import OpenAI
client = OpenAI()

tools = [
  {
    "type": "function",
    "function": {
      "name": "get_current_weather",
      "parameters": {
        "type": "object",
        "properties": {
          "location": {
            "type": "string",
          },
          "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
        },
        "required": ["location"],
        "additionalProperties": False,
      },
    }
  }
]
messages = [{"role": "user", "content": "What's the weather like in Boston today?"}]
completion = client.chat.completions.create(
  model="gpt-4o-mini",
  messages=messages,
  tools=tools,
  tool_choice="auto"
)

function_call = completion.choices[0].message.tool_calls[0].function
print(function_call)
""" output:
Function(arguments='{"location":"Boston, MA"}', name='get_current_weather')
"""

# print(completion)
""" output:
ChatCompletion(
    id='chatcmpl-APsKM5qRGRupcN6yLIKFItOIyLdCK', 
    choices=[
        Choice(
            finish_reason='tool_calls', 
            index=0, 
            logprobs=None, 
            message=ChatCompletionMessage(
                content=None, 
                refusal=None, 
                role='assistant', 
                audio=None, 
                function_call=None, 
                tool_calls=[
                    ChatCompletionMessageToolCall(
                        id='call_eFhJoXCaDKxwmVeSz4PeAAiR', 
                        function=Function(
                            arguments='{"location":"Boston, MA"}', 
                            name='get_current_weather'
                        ), 
                        type='function'
                    )
                ]
            )
        )
    ], 
    created=1730730398, 
    model='gpt-4o-mini-2024-07-18', 
    object='chat.completion', 
    service_tier=None, 
    system_fingerprint='fp_0ba0d124f1', 
    usage=CompletionUsage(completion_tokens=17, prompt_tokens=80, total_tokens=97, completion_tokens_details=CompletionTokensDetails(audio_tokens=None, reasoning_tokens=0), prompt_tokens_details=PromptTokensDetails(audio_tokens=None, cached_tokens=0)))
"""
